class Solution(object): def zigzagLevelOrder(self, root): tree = [] if not root: return tree curr_level = [root] direction = 'L' # print(type(root), type(curr_level)) # (<class 'precompiled.treenode.TreeNode'>, <type 'list'>) # print(curr_level) # 作为list,却并不能遍历整个树 while curr_level: level_list = [] next_level = [] for temp in curr_level: level_list.append(temp.val) if temp.left: next_level.append(temp.left) if temp.right: next_level.append(temp.right) if direction == 'L': tree.append(level_list) direction = 'R' else: tree.append(level_list[::-1]) direction = 'L' curr_level = next_level return tree
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None
class Solution: # @param root, a tree node # @return a list of lists of integers def preorder(self, root, level, res): if root: if len(res) < level+1: res.append([]) if level % 2 == 0: res[level].append(root.val) else: res[level].insert(0, root.val) # 向0位置插入 self.preorder(root.left, level+1, res) self.preorder(root.right, level+1, res) def zigzagLevelOrder(self, root): res=[] self.preorder(root, 0, res) return res